package com.qlylkj.lbk.ui.user.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.qlylkj.lbk.app.PreferenceHelper
import com.qlylkj.lbk.base.BaseViewModel
import com.qlylkj.lbk.model.api.ResultResponse
import com.qlylkj.lbk.model.repository.UserRepository

class LoginViewModel: BaseViewModel() {

    private val _uiState = MutableLiveData<LoginUiModel>()
    val uiState: LiveData<LoginUiModel>
        get() = _uiState

    private val userRepository by lazy { UserRepository() }

    private fun emitUiState(
        showError: String? = null,
        loginSuccess: Boolean = false
    ) {
        val uiModel = LoginUiModel(showError,loginSuccess)
        _uiState.value = uiModel
    }

    data class LoginUiModel(
        val showError: String?,
        val loginSuccess: Boolean
    )

    fun login(username: String,password: String){
        launch {
            val result = userRepository.login(username, password)
            if (result is ResultResponse.SuccessEntity) {
                PreferenceHelper.setUser(result.data)
                emitUiState(loginSuccess = true)
            } else if (result is ResultResponse.Error) {
                emitUiState(showError = result.exception.message)
            }
        }
    }

}